package com.wjw.java.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * FutureTask:能够接受Callable类型的参数,用来处理有返回结果的情况
 */
@Slf4j(topic = "c._03FutureTask")
public class _03FutureTask {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        test1();
        test2();
        log.debug("主线程...");
    }

    /**
     * 完整写法
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void test1() throws ExecutionException, InterruptedException {
        //创建任务对象
        FutureTask<Integer> task1 = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                log.debug("task1...");
                Thread.sleep(1000);
                return 100;
            }
        });

        //参数1：任务对象,参数2线程名称
        Thread t1 = new Thread(task1,"t1");
        t1.start();

        //获取返回结果:主线程会被阻塞,同步等待task1执行完毕结果
        Integer res = task1.get();
        log.debug("res:"+res);
    }

    /**
     * lambda简写
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void test2() throws ExecutionException, InterruptedException {
        //创建任务对象
        FutureTask<Integer> task2 = new FutureTask<Integer>(() ->{
            log.debug("task2...");
            Thread.sleep(1000);
            return 100;
        });

        //参数1：任务对象,参数2线程名称
        Thread t2 = new Thread(task2,"t2");
        t2.start();

        //获取返回结果:主线程会被阻塞,同步等待task1执行完毕结果
        Integer res = task2.get();
        log.debug("res:"+res);
    }
}
